<?php
/**
 * @author Brian Voss
 */
class TwitterController extends Social_Oauth_BaseController {
	/**
	 * @var String
	 */
    protected $serviceKey = 'twitter';
	/**
	 * @var Zend_Service_Twitter_Search 
	 */
    protected $searchApi;
	/**
	 * Initialization 
	 */
	public function init()
	{
		parent::init();
		$this->searchApi = new Zend_Service_Twitter_Search();
	}
	/**
	 * Default Page 
	 */
	public function indexAction()
	{
		$authenticated = $this->isAuthenticated();
		if ( $this->isAuthenticated() )
		{
			$model = new Application_Model_Twitter(
				unserialize($this->session->token), 
				$this->config->oauth->params->toArray()
			);
			$feed = $model->getProfile();
			var_dump($feed);
		}
		
		echo $authenticated ? "logged in" : "not logged in";
	}
	/**
	 * Start authentication 
	 */
	public function startauthAction()
	{
		parent::startauth();
	}
	/**
	 * Complete authentication
	 */
	public function finishauthAction()
	{
		parent::finishauth();
		if ( $this->isAuthenticated() )
		{
			echo "worked!";
		}
		else
		{
			echo "didn't work";
		}
	}
	/**
	 * Show my tweets 
	 */
	public function myfeedAction()
	{
		$params = $this->getRequest()->getParams();
		$this->_helper->layout->disableLayout();
		// Get the Twitter params from config
		$userToken			= $this->config->api->access_token;
		$userSecret			= $this->config->api->token_secret;
		$appConsumerKey		= $this->config->api->consumer_key;
		$appConsumerSecret	= $this->config->api->consumer_secret;
		// Create the Oauth Token
		$token = new Zend_Oauth_Token_Access();
		$token->setToken($userToken)->setTokenSecret($userSecret);
		// Create the Twitter Service object
		$options = array(
			'accessToken'    => $token,
			'consumerKey'    => $appConsumerKey,
			'consumerSecret' => $appConsumerSecret);
		$twitter = new Zend_Service_Twitter($options);
		// Get my tweets
		$tweets = $twitter->statusFriendsTimeline();
		var_dump($tweets);die();
		// Send JSON to browser
		$this->getResponse()
			->setHeader(Zend_Http_Client::CONTENT_TYPE, 'application/json')
			->appendBody(json_encode($tweets));
	}
	/**
	 * Twitter Search Endpoint 
	 */
    public function searchAction()
    {
		Zend_Layout::getMvcInstance()->disableLayout();
		$params = $this->getRequest()->getParams();

		$search = array_key_exists("q", $params) ? $params["q"] : null;	
		$response = $this->searchApi->search($search);

		$this->getResponse()
			->setHeader(Zend_Http_Client::CONTENT_TYPE, 'application/json')
			->appendBody(json_encode($response));
    }
}